import request from '../../../../utils/axiosutils'
import types from '../../../mutation-types'
import { getSessionKey } from '../../../../utils/utils'

const state = {
  // 菜单列表
  menuList: [],
  sidebar: {
    // 侧边开关
    collapsed: getSessionKey('state.sidebar.collapsed', false)
  },
  // 屏幕信息
  viewInfo: {},
  tabsRouter: getSessionKey('state.tabsRouter', [])
}

const getters = {
  menuList: state => state.menuList,
  sidebar: state => state.sidebar,
  viewInfo: state => state.viewInfo,
  tabsRouter: state => state.tabsRouter
}

const mutations = {
  /** 菜单 */
  [types.MENU_LIST] (state, menu) {
    state.menuList = menu
  },
  /** 侧边开关  */
  [types.SIDEBAR] (state, collapsed) {
    state.sidebar.collapsed = collapsed
    window.sessionStorage.setItem('state.sidebar.collapsed', JSON.stringify(collapsed))
  },
  /** 屏幕信息  */
  [types.VIEW_INFO] (state, screenInfo) {
    state.viewInfo = screenInfo
  },
  /** 屏幕信息 ScreenWidth */
  [types.VIEW_INFO_SCREEN_WIDTH] (state, screenWidth) {
    state.viewInfo.screenWidth = screenWidth
  },
  /** 屏幕信息 ScreenHeight */
  [types.VIEW_INFO_SCREEN_HEIGHT] (state, screenHeight) {
    state.viewInfo.screenHeight = screenHeight
  },
  /** 选择路由  */
  [types.TABS_ROUTER] (state, tabsRouter) {
    // 选择路由
    state.tabsRouter.push(tabsRouter)
    window.sessionStorage.setItem('state.tabsRouter', JSON.stringify(state.tabsRouter))
  },
  /** 清空保存选择路由  */
  [types.CLEAR_TABS_ROUTER] (state, tabsRouter) {
    state.tabsRouter = tabsRouter
    window.sessionStorage.removeItem('state.tabsRouter')
  },
  /** 移除选择路由 */
  [types.DEL_TABS_ROUTER] (state, delTabsRouter) {
    state.tabsRouter.splice(state.tabsRouter.indexOf(delTabsRouter), 1)
    window.sessionStorage.setItem('state.tabsRouter', JSON.stringify(state.tabsRouter))
  }
}

const actions = {
  /**
   * 获取权限列表
   *
   * @param commit
   * @param rootState
   * @returns {Promise<any>}
   */
  getPermission: function ({commit, rootState}) {
    return new Promise((resolve, reject) => {
      let token = rootState.user.token
      console.log('在rootState中取出token查询权限列表:', rootState)
      const url = '/sysm/navlist'
      const params = {token: token}
      request.axiosCall(url, params).then((res) => {
        // 存储权限列表
        commit(types.MENU_LIST, res.data)
        resolve(res.data)
      }).catch((error) => {
        reject(error)
      })
    })
  },
  /**
   * 清空权限列表
   *
   * @param commit
   * @param rootState
   */
  clearMenuList: function ({commit, rootState}) {
    commit(types.MENU_LIST, [])
  },
  /**
   * 清空保存选择路由
   *
   * @param commit
   * @param rootState
   */
  clearTabsRouter: function ({commit, rootState}) {
    commit(types.CLEAR_TABS_ROUTER, [])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
